#include  "scheduler.h"

uint8_t task_num;		//计算当前任务数量

//任务创建模板
typedef struct {
	void (*task_func)(void);
	uint32_t rate_ms;
	uint32_t last_ms;
	uint32_t start_time;
	uint8_t is_stuck;
} task_t;

static task_t scheduler_task[] = {
	{printf_info_task, 1000, 0, 0, 0},
	{getsture_handler_task, 200, 0, 0, 0},
	{motor_handler_task, 300, 0, 0, 0},
	{servos_handler_task, 21, 0, 0, 0},
};

/**
 * 任务初始化
 */
void scheduler_init(void) {
	task_num = sizeof(scheduler_task) / sizeof(task_t);
}

/**
 * 任务运行
 */
void scheduler_run(void) {
	for (int i = 0; i < task_num; i++) {
		uint32_t now_time = get_tickms;
		if (now_time >= scheduler_task[i].rate_ms + scheduler_task[i].last_ms) {
			if (scheduler_task[i].is_stuck) {
				// 如果任务卡死，重置任务状态
				scheduler_task[i].last_ms = now_time;
				scheduler_task[i].start_time = now_time;
				scheduler_task[i].is_stuck = 0;
			} else {
				scheduler_task[i].start_time = now_time;
				scheduler_task[i].task_func();
				scheduler_task[i].last_ms = now_time;
			}
		}
		// 检查任务是否卡死
		if (scheduler_task[i].start_time && (now_time - scheduler_task[i].start_time > scheduler_task[i].rate_ms * 2)) {
			scheduler_task[i].is_stuck = 1;
		}
	}
}

